<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    title="用户选择"
    width="800px"
    @close="handleClose"
  >
    <div class="custom-table-list-wrapper">
      <div class="search" :class="{ active: toggleSearchStatus }">
        <div class="search-left" ref="searchFromRef">
          <el-form class="search-form" inline>
            <el-form-item label="关键词">
              <el-input
                class="search-input"
                v-model="searchParams.keyWord"
                placeholder="请输入真实姓名"
                :suffix-icon="Search"
              ></el-input>
            </el-form-item>
          </el-form>
          <a
            class="search-left-toggle"
            v-if="showToggle"
            @click="handleToggleSearch"
          >
            <svg-icon :name="toggleSearchStatus ? 'up' : 'down'" />
            {{ toggleSearchStatus ? '收起' : '展开' }}
          </a>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="initTableListAndSelect(1)"
            ><svg-icon name="search" size="14px" />搜索</el-button
          >
          <el-button @click="handleReset()"
            ><svg-icon name="reset" size="17px" />重置</el-button
          >
        </div>
      </div>
      <div class="content">
        <div class="content-table">
          <el-table
            class="custom-table"
            ref="tableRef"
            :data="tableData"
            @select="handleSelectOne"
            @select-all="handleSelectAll"
          >
            <el-table-column type="selection" width="60" />
            <el-table-column prop="loginName" label="用户名" />
            <el-table-column prop="userName" label="真实姓名" />
            <el-table-column prop="deptName" label="部门" />
            <el-table-column prop="userPhone" label="手机号码" />
          </el-table>
        </div>
        <div class="content-page">
          <el-pagination
            class="custom-pagination"
            :current-page="paginationParams.pageIndex"
            :page-size="paginationParams.pageSize"
            background
            :page-sizes="[10, 20, 30, 50]"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="initTableListAndSelect"
          />
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="handleClose(false)" :loading="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useTableList } from '@/hooks/useTableList'
import { getNoRoleList, roleAddUser } from '@/api/manager/systemManage/role.js'
import { ElMessage } from 'element-plus'
const props = defineProps({
  roleId: {
    type: String,
  },
})
const searchParams = ref({})
const {
  Search,
  toggleSearchStatus,
  showToggle,
  handleToggleSearch,
  tableData,
  paginationParams,
  total,
  initTableList,
  handleSizeChange,
  handleReset,
  searchFromRef,
} = useTableList(searchParams, getNoRoleList)
const tableRef = ref()
const multipleSelection = ref([])
const emit = defineEmits(['close'])
const dialogVisible = ref(false)
const handleClose = (isLoad) => {
  multipleSelection.value = []
  tableRef.value && tableRef.value.clearSelection()
  dialogVisible.value = false
  emit('close', isLoad)
}
const loading = ref(false)
const handleSubmit = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择用户')
    return
  }
  const userIds = multipleSelection.value.map((i) => {
    return i.pkid
  })
  const params = { roleId: props.roleId, userIds: userIds }
  loading.value = true
  try {
    const res = await roleAddUser(params)
    if (res.success) {
      ElMessage({
        type: 'success',
        message: '用户角色赋值成功',
      })
      handleClose(true)
    } else {
      ElMessage.error(res.message)
    }
    loading.value = false
  } catch (error) {
    console.log(error)
    loading.value = false
  }
}
const handleSelectOne = (selection, row) => {
  // 判断是选中/不选中
  const index = selection.findIndex((i) => i.pkid === row.pkid)
  if (index !== -1) {
    multipleSelection.value.push(row)
  } else {
    multipleSelection.value.splice(index, 1)
  }
}
const handleSelectAll = (selection) => {
  // 判断全选/全不选
  if (selection.length > 0) {
    selection.forEach((row) => {
      const index = multipleSelection.value.findIndex(
        (i) => i.pkid === row.pkid,
      )
      if (index === -1) {
        multipleSelection.value.push(row)
      }
    })
  } else {
    tableData.value.forEach((row) => {
      const index = multipleSelection.value.findIndex(
        (i) => i.pkid === row.pkid,
      )
      if (index !== -1) {
        multipleSelection.value.splice(index, 1)
      }
    })
  }
}
const initTableListAndSelect = async (pageIndex) => {
  await initTableList(pageIndex)
  nextTick(() => {
    if (multipleSelection.value.length > 0) {
      tableData.value.forEach((row) => {
        const isHas = multipleSelection.value.find((i) => i.pkid === row.pkid)
        isHas && tableRef.value && tableRef.value.toggleRowSelection(row, true)
      })
    }
  })
}
watch(
  () => dialogVisible.value,
  async () => {
    if (dialogVisible.value) {
      initTableListAndSelect(1)
    }
  },
)
defineExpose({ dialogVisible })
onMounted(() => {})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/table.scss';
.search {
  padding: 0;
  margin: 0;
  box-shadow: none;
  height: auto;
}
.content {
  padding: 0;
}
</style>
